package com.tarena.lbs.user.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.user.dao.mapper.UserMapper;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.query.UserQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Slf4j
public class UserRepositoryImpl implements UserRepository {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserPO getByPhone(String phone) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Long countUserByPhone(String phone) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("phone",phone);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public void save(UserPO poParam) {
        userMapper.insert(poParam);
    }

    @Override
    public UserPO getById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public PageInfo<UserPO> SelectPageList(UserQuery query) {
        log.info("用户列表查询，入参：{}", query);
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();

        // 用户姓名 模糊查询
        if (StringUtils.isNotBlank(query.getUserName())){
            queryWrapper.like("user_name", query.getUserName());
        }
        if (StringUtils.isNotBlank(query.getPhone())){
            queryWrapper.eq("phone", query.getPhone());
        }
        // 修改这里：使用正确的字段名 provider_type
        if (StringUtils.isNotBlank(query.getChannelSource())){
            queryWrapper.eq("provider_type", query.getChannelSource());
        }
        if (query.getRegisterTimeStart() != null){
            queryWrapper.ge("reg_time", query.getRegisterTimeStart());
        }
        if (query.getRegisterTimeEnd() != null){
            queryWrapper.le("reg_time", query.getRegisterTimeEnd());
        }
        queryWrapper.orderByDesc("id");

        // 修改这里：将 queryWrapper 传入 selectList
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<UserPO> pos = userMapper.selectList(queryWrapper);
        return new PageInfo<>(pos);
    }
}
